package com.javaee.wordtree.service;

import com.javaee.wordtree.entity.Message;
import com.javaee.wordtree.entity.MessageWithRagInfo;
import com.javaee.wordtree.util.RagInfoUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息RAG信息转换服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MessageRagService {

    private final RagInfoUtil ragInfoUtil;

    /**
     * 将Message实体转换为MessageWithRagInfo
     * 
     * @param message Message实体
     * @return MessageWithRagInfo实体
     */
    public MessageWithRagInfo convertToMessageWithRagInfo(Message message) {
        MessageWithRagInfo messageWithRagInfo = new MessageWithRagInfo(message);

        // 如果消息包含RAG信息，则构建RAG增强信息对象
        if (Boolean.TRUE.equals(message.getBasedOnRag())) {
            MessageWithRagInfo.RagEnhancementInfo ragInfo = new MessageWithRagInfo.RagEnhancementInfo();

            ragInfo.setBasedOnRag(message.getBasedOnRag());
            ragInfo.setRagCount(message.getRagCount());
            ragInfo.setValidRagCount(message.getValidRagCount());
            ragInfo.setAverageSimilarity(message.getAverageSimilarity());
            ragInfo.setMaxSimilarity(message.getMaxSimilarity());
            ragInfo.setMinSimilarity(message.getMinSimilarity());
            ragInfo.setSimilarityThreshold(message.getSimilarityThreshold());

            // 解析RAG结果JSON
            if (message.getRagResults() != null) {
                List<MessageWithRagInfo.RagResultSummary> ragResults = ragInfoUtil
                        .jsonToRagResults(message.getRagResults());
                ragInfo.setRagResults(ragResults);
            }

            messageWithRagInfo.setRagInfo(ragInfo);
        }

        return messageWithRagInfo;
    }

    /**
     * 批量转换Message列表为MessageWithRagInfo列表
     * 
     * @param messages Message列表
     * @return MessageWithRagInfo列表
     */
    public List<MessageWithRagInfo> convertToMessageWithRagInfoList(List<Message> messages) {
        return messages.stream()
                .map(this::convertToMessageWithRagInfo)
                .collect(Collectors.toList());
    }

    /**
     * 将MessageWithRagInfo转换为Message实体（用于保存到数据库）
     * 
     * @param messageWithRagInfo MessageWithRagInfo实体
     * @return Message实体
     */
    public Message convertToMessage(MessageWithRagInfo messageWithRagInfo) {
        Message message = new Message();

        message.setMessageId(messageWithRagInfo.getMessageId());
        message.setChatId(messageWithRagInfo.getChatId());
        message.setText(messageWithRagInfo.getText());
        message.setIsUser(messageWithRagInfo.getIsUser());
        message.setCreatedTime(messageWithRagInfo.getCreatedTime());

        // 如果包含RAG信息，则设置相关字段
        MessageWithRagInfo.RagEnhancementInfo ragInfo = messageWithRagInfo.getRagInfo();
        if (ragInfo != null) {
            message.setBasedOnRag(ragInfo.getBasedOnRag());
            message.setRagCount(ragInfo.getRagCount());
            message.setValidRagCount(ragInfo.getValidRagCount());
            message.setAverageSimilarity(ragInfo.getAverageSimilarity());
            message.setMaxSimilarity(ragInfo.getMaxSimilarity());
            message.setMinSimilarity(ragInfo.getMinSimilarity());
            message.setSimilarityThreshold(ragInfo.getSimilarityThreshold());

            // 将RAG结果转换为JSON字符串
            if (ragInfo.getRagResults() != null) {
                String ragResultsJson = ragInfoUtil.ragResultsToJson(ragInfo.getRagResults());
                message.setRagResults(ragResultsJson);
            }
        } else {
            // 如果没有RAG信息，设置默认值
            message.setBasedOnRag(false);
        }

        return message;
    }

    /**
     * 根据API响应格式创建MessageWithRagInfo
     * 
     * @param chatId  聊天ID
     * @param text    消息文本
     * @param isUser  是否为用户消息
     * @param ragInfo RAG增强信息
     * @return MessageWithRagInfo实体
     */
    public MessageWithRagInfo createMessageWithRagInfo(Integer chatId, String text, Boolean isUser,
            MessageWithRagInfo.RagEnhancementInfo ragInfo) {
        MessageWithRagInfo messageWithRagInfo = new MessageWithRagInfo();
        messageWithRagInfo.setChatId(chatId);
        messageWithRagInfo.setText(text);
        messageWithRagInfo.setIsUser(isUser);
        messageWithRagInfo.setCreatedTime(new java.util.Date());
        messageWithRagInfo.setRagInfo(ragInfo);

        return messageWithRagInfo;
    }
}
